//@author A0087191Y
package net.mysoc.w111j.service.actions;

import java.util.List;

import net.mysoc.w111j.model.BadCategoryNameException;
import net.mysoc.w111j.model.Category;
import net.mysoc.w111j.model.Expense;
import net.mysoc.w111j.model.User;

/**
 * An {@code Action} to undo the deleting of a {@code Category}.
 */
public class DeleteCategoryAction implements Action {
    private final User user;
    private final Category oldCategory;
    private final List<Expense> affectedExpenses;
    private String status;

    public DeleteCategoryAction(User user, Category oldCategory, List<Expense> affectedExpenses) {
        this.user = user;
        this.oldCategory = oldCategory;
        this.affectedExpenses = affectedExpenses;
        setStatus(oldCategory);
    }

    @Override
    public void undo() {
        try {
            user.updateCategory(oldCategory);
        } catch (BadCategoryNameException e) {
            // This is guaranteed to not happen here.
            throw new RuntimeException(e);
        }
        for (Expense e : affectedExpenses) {
            e.setCategory(oldCategory);
        }
    }

    private void setStatus(Category category) {
        status = "Category deleted: " + category.getName() + ".";
    }

    @Override
    public String getStatus() {
        return status;
    }
}
